package com.hzit.custom;

import lombok.Data;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.AfterRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;


@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {
	public AgeRoutePredicateFactory() {
		super(Config.class);
	}
	@Override
	public List<String> shortcutFieldOrder() {
		return Arrays.asList("min","max");
	}

	@Override
	public Predicate<ServerWebExchange> apply(AgeRoutePredicateFactory.Config config) {
		return exchange -> {
			//1. 得到请求参数age
			String ageStr = exchange.getRequest().getQueryParams().getFirst("age");
			//2. 转换为整数
			Integer age = Integer.parseInt(ageStr);
			return age >= config.getMin() && age <= config.getMax();
		};
	}
	@Data
	public static class Config {
		private Integer min;
		private Integer max;
	}
}
